<?php

namespace Tests\Feature\Base;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;

class BaseTestCase extends TestCase
{
    public string $dbName = 'kf_rms';

    public static bool $isCreateNewDb = true; // 是否创建新的数据库

    public static bool $isCreated = false; // 不要修改这个值

    public function __construct(?string $name = null, array $data = [], $dataName = '')
    {
        if (self::$isCreateNewDb) {
            $this->dbName = env('APP_NAME', '') . '_' . Str::random();
        }

        parent::__construct($name, $data, $dataName);
    }

    public function setUp(): void
    {
        parent::setUp();

        if (self::$isCreateNewDb && !self::$isCreated) {
            $this->setUpConnections();
            $this->runDatabaseMigrations();
        }
    }

    public function setUpConnections()
    {
        $this->createDatabase();

        \Config::set('database.connections.mysql.database', $this->dbName);
        DB::reconnect();
        DB::connection();

    }

    public function runDatabaseMigrations()
    {
        $this->artisan('migrate:install');
        $this->artisan('migrate');
        $this->artisan('db:seed');

        $this->beforeApplicationDestroyed(function () {
//            if (!$this->hasFailed()) {
            $this->dropDatabase();
//            }
        });

        self::$isCreated = true;
    }

    public function createDatabase()
    {
        $sql = 'CREATE DATABASE `' . $this->dbName . '`';

        DB::select($sql);
    }

    public function dropDatabase()
    {
        $sql = 'DROP DATABASE `' . $this->dbName . '`';

        DB::select($sql);
    }
}
